package com.llpy.Service;

import com.llpy.dto.SongDto;
import com.llpy.mapper.SingerMapper;
import com.llpy.mapper.SongMapper;
import com.llpy.pojo.Singer;
import com.llpy.pojo.Song;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class SongService {
    @Autowired
    private SongMapper songRepository;
    @Autowired
    private MusicService musicService;
    @Autowired
    private SingerMapper singerRepository;

    //添加歌曲
    public Song saveSongAndSinger(SongDto song) {
        song.setName(song.getName().trim());
        song.setSingerName(song.getSingerName().trim());    //将歌手和歌名的前后空格删除
        //判断传入的song中歌手是否存在
        Singer singer = singerRepository.findByName(song.getSinger().getName());
        if(singer==null){
//            为空新建歌手
            Singer sig = new Singer();
            sig.setName(song.getSinger().getName());
            singerRepository.save(sig);
            song.setSinger(sig);
        }else{
//            否则直接将singer赋值给传进来的song
            song.setSinger(singer);
        }
        //得到所有歌曲名相等的集合
        List<SongDto> byName = songRepository.findByName(song.getName());
        for (SongDto songDto : byName) {
//            遍历判断是否歌手或歌曲都相等
            if(songDto.getSingerName().equals(song.getSinger().getName()) && songDto.getName().equals(song.getName())){
//                相等返回null
                return null;
            }
        }
        //如果不相等，则当作一条新得歌曲存入
        song.setId(null);
        return songRepository.save(song);
    }

    //查询歌手
    public Singer getBySinger(String name){
        //根据传入的名字查询
        Singer singer = singerRepository.findByName(name.trim());
        if(singer==null){
            return null;
        }else{
            singer.setSong(songRepository.findBySinger(singer));
            return singer;
        }
    }

    //查询歌曲
    public List<SongDto> getBySong(String name){
        //根据歌曲名查询
        return songRepository.findByName(name);
    }

    //查询全部歌曲

    public List<Song> getAllSong(){

        return songRepository.findAll();
    }

    //删除歌曲
    public boolean deleteSong(String id){
//        根据传入的id删除歌曲
        Optional<Song> byId = songRepository.findById(id);
        if (byId.isPresent()) {
            Song song = byId.get();
//            删除音乐文件
            ObjectId music = new ObjectId(song.getMusicId());
            musicService.deleteMusic(music);
            songRepository.delete(song);
            return true;
        }
        return false;
    }
}
